package com.enmotech.kafkatest.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.UUID;

/**
 * com.enmotech.kafkatest.controller
 *
 * @author syf
 * @create 2022-08-12-17:46
 * @Description kafka-test
 */

@RestController
@Slf4j
public class Producer {
    String[] type = new String[]{"世界名著","科普丛书","家常菜谱","玄幻小说","言情小说"};
    String[] name = new String[]{"红高粱","檀香刑","卡拉马佐夫兄弟","变形记","城堡"};
    String[] description = new String[]{"好看指数一颗星","好看指数二颗星","好看指数三颗星","好看指数四颗星","好看指数五颗星"};
    String message;
    String message2;
    Random random = new Random();
    @Autowired
    private KafkaTemplate<String, String> template;

    @RequestMapping("/springKafkaSend")
    public String send(){
        //将消息发送到Kafka服务器的名称为“test”的Topic中
        for (int i = 2; i < 22; i++) {
            int r = random.nextInt(5);
            message = "{\"schema\":" +
                    "{\"type\":\"struct\",\"fields\":" +
                    "[{\"type\":\"int32\",\"optional\":false,\"field\":\"id\"}," +
                    "{\"type\":\"string\",\"optional\":true,\"field\":\"type\"}," +
                    "{\"type\":\"string\",\"optional\":true,\"field\":\"name\"}," +
                    "{\"type\":\"string\",\"optional\":true,\"field\":\"description\"}]," +
                    "\"optional\":false,\"name\":\"tbl_book\"},\"" +
                    "payload\":{\"id\":"+i+",\"type\":\""+type[r]+"\",\"name\":\""+name[r]+"\",\"description\":\""+description[r]+"\"}}";
            message2 = "{\"schema\":{\"type\":\"struct\",\"fields\":[{\"type\":\"int32\",\"optional\":false,\"field\":\"id\"},{\"type\":\"double\",\"optional\":true,\"field\":\"longitude\"},{\"type\":\"double\",\"optional\":true,\"field\":\"latitude\"},{\"type\":\"double\",\"optional\":true,\"field\":\"temperature\"},{\"type\":\"double\",\"optional\":true,\"field\":\"humidity\"},{\"type\":\"int64\",\"optional\":true,\"name\":\"org.apache.kafka.connect.data.Timestamp\",\"version\":1,\"field\":\"tabletime\"},{\"type\":\"string\",\"optional\":true,\"field\":\"stringtime\"},{\"type\":\"string\",\"optional\":true,\"field\":\"randomstring\"}],\"optional\":false,\"name\":\"demo_table\"},\"payload\":{\"id\":1,\"longitude\":118.7976264128418,\"latitude\":31.969325071306,\"temperature\":38.0,\"humidity\":87.4,\"tabletime\":1660832777000,\"stringtime\":\"2022-8-18 14:23:09\",\"randomstring\":\"对不起我是警察，一枪打死你\"}}";
            this.template.send("test", message2);
            /*this.template.send("test2", message);
            this.template.send("test3", message);
            this.template.send("test4", message);*/
            log.info("message: {}", message);
        }
        return message;
    }
}
